#include "controlform.h"
#include "ui_controlform.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QDoubleSpinBox>
#include <QPushButton>
#include <QSlider>
#include <QGroupBox>
#include <QPainter>
#include <QStyleOption>
#include <QSettings>
#include <QLabel>
#include "savepostipsdialog.h"


ControlForm::ControlForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ControlForm)
{
    ui->setupUi(this);
    this->setFixedHeight(300);
    this->setProperty("form","backgroundform");
    ui->label_xy->setProperty("model","level1");
    ui->label_z->setProperty("model","level1");

    ui->widget_8->setProperty("form","whitepanel");
    ui->widget_9->setProperty("form","whitepanel");
    ui->widget_10->setProperty("form","whitepanel");

    ui->pushButton_lockx->setHidden(true);
    ui->pushButton_locky->setHidden(true);
    ui->pushButton_lockz->setHidden(true);

    connect(ui->verticalSlider, &QSlider::valueChanged, this, &ControlForm::updateLabel);
    connect(ui->widget_qhControl, &QhControllerForm::sig_directionKeyPressed, this, &ControlForm::handleDirectionKeyPressed);


}

ControlForm::~ControlForm()
{
    delete ui;
}

void ControlForm::ShowLabelImage(QLabel *label, int level)
{
    switch (level) {
    case 0:
        label->setProperty("model","level0");
        break;
    case 1:
        label->setProperty("model","level1");
        break;
    case 2:
        label->setProperty("model","level2");
        break;
    case 3:
        label->setProperty("model","level3");
        break;
    default:
        break;
    }
    // 强制样式更新
    label->style()->unpolish(label);
    label->style()->polish(label);
    label->update();
}

void ControlForm::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.init(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget,&opt,&painter,this);
    QWidget::paintEvent(event);
}

void ControlForm::on_pushButton_minusXYSpeed_clicked()
{
    if(m_speedXYLevel>0)
        --m_speedXYLevel;
    ShowLabelImage(ui->label_xy,m_speedXYLevel);
}

void ControlForm::on_pushButton_addXYSpeed_clicked()
{
    if(m_speedXYLevel<3)
        ++m_speedXYLevel;
    ShowLabelImage(ui->label_xy,m_speedXYLevel);
}

void ControlForm::on_pushButton_minusZSpeed_clicked()
{
    if(m_speedZLevel>1)
        --m_speedZLevel;
    ShowLabelImage(ui->label_z,m_speedZLevel);
}

void ControlForm::on_pushButton_addZSpeed_clicked()
{
    if(m_speedZLevel<3)
        ++m_speedZLevel;
    ShowLabelImage(ui->label_z,m_speedZLevel);
}

#include <QDebug>
void ControlForm::updateLabel(int value)
{
    qDebug()<<"current Value" <<value;

    double currentValue = value/100000.00;
    ui->label_abz->setText(QString::number(currentValue));
    emit sig_labelChanged(ui->label_abz->text());

}

void ControlForm::updateButtonStates(QPushButton *clickedButton) {
    // 定义互斥按钮组
    QList<QPushButton*> buttons = {
        ui->pushButton_relativeMove,
        ui->pushButton_moveToAbsolutePos,
        ui->pushButton_repositionToTheReferencePoint
    };

    // 遍历按钮组，确保只有点击的按钮是 checked 状态
    for (QPushButton *button : buttons) {
        if (button != clickedButton) {
            button->setChecked(false);
        }
    }
}

void ControlForm::on_pushButton_relativeMove_clicked(bool checked) {
    if (checked) {
        updateButtonStates(ui->pushButton_relativeMove);
        ui->pushButton_lockx->setHidden(true);
        ui->pushButton_locky->setHidden(true);
        ui->pushButton_lockz->setHidden(true);
    }
    // 根据 checked 状态设置 lineEdit 的 enable 状态
    ui->lineEdit_x->setEnabled(checked);
    ui->lineEdit_y->setEnabled(checked);
    ui->lineEdit_z->setEnabled(checked);
}

void ControlForm::on_pushButton_moveToAbsolutePos_clicked(bool checked) {
    if (checked) {
        updateButtonStates(ui->pushButton_moveToAbsolutePos);
        ui->pushButton_lockx->setHidden(false);
        ui->pushButton_locky->setHidden(false);
        ui->pushButton_lockz->setHidden(false);

        ui->pushButton_lockx->setChecked(!ui->lineEdit_x->isEnabled());
        ui->pushButton_locky->setChecked(!ui->lineEdit_y->isEnabled());
        ui->pushButton_lockz->setChecked(!ui->lineEdit_z->isEnabled());

    }
    // 添加绝对位置移动的逻辑
}

void ControlForm::on_pushButton_repositionToTheReferencePoint_clicked(bool checked) {
    if (checked) {
        updateButtonStates(ui->pushButton_repositionToTheReferencePoint);
        ui->pushButton_lockx->setHidden(true);
        ui->pushButton_locky->setHidden(true);
        ui->pushButton_lockz->setHidden(true);
    }
    // 添加参考点重定位的逻辑
}

void ControlForm::updateRelativePositions() {
    if (ui->pushButton_savePos1->isChecked()) {
        double currentAbx = ui->label_abx->text().toDouble();
        double currentAby = ui->label_aby->text().toDouble();
        double currentAbz = ui->label_abz->text().toDouble();

        ui->label_rex->setText(QString::number(currentAbx - m_savedAbx, 'f', 4));
        ui->label_rey->setText(QString::number(currentAby - m_savedAby, 'f', 4));
        ui->label_rez->setText(QString::number(currentAbz - m_savedAbz, 'f', 4));
    }
}

void ControlForm::on_pushButton_execute_clicked() {
    if (ui->pushButton_relativeMove->isChecked()) {
        // 获取 lineEdit 的值并转换为 double
        double dx = ui->lineEdit_x->text().replace("mm","").toDouble();
        double dy = ui->lineEdit_y->text().replace("mm","").toDouble();
        double dz = ui->lineEdit_z->text().replace("mm","").toDouble();

        // 更新绝对位置的值
        double newAbx = ui->label_abx->text().toDouble() + dx;
        double newAby = ui->label_aby->text().toDouble() + dy;
        double newAbz = ui->label_abz->text().toDouble() + dz;

        // 设置新的绝对位置值
        ui->label_abx->setText(QString::number(newAbx, 'f', 4));
        ui->label_aby->setText(QString::number(newAby, 'f', 4));
        ui->label_abz->setText(QString::number(newAbz, 'f', 4));
        emit sig_labelChanged(ui->label_abz->text());
    }
    else if (ui->pushButton_moveToAbsolutePos->isChecked()) {
        // 获取 lineEdit 的值并转换为 double
        double dx = ui->lineEdit_x->text().replace("mm","").toDouble();
        double dy = ui->lineEdit_y->text().replace("mm","").toDouble();
        double dz = ui->lineEdit_z->text().replace("mm","").toDouble();
        // 设置新的绝对位置值
        ui->label_abx->setText(QString::number(dx, 'f', 4));
        ui->label_aby->setText(QString::number(dy, 'f', 4));
        ui->label_abz->setText(QString::number(dz, 'f', 4));
        emit sig_labelChanged(ui->label_abz->text());
    }
}

void ControlForm::handleDirectionKeyPressed(int direction) {
    switch (direction) {
    case 0: // 上
        ui->label_aby->setText(QString::number(ui->label_aby->text().toDouble() + 1));
        break;
    case 2: // 下
        ui->label_aby->setText(QString::number(ui->label_aby->text().toDouble() - 1));
        break;
    case 1: // 左
        ui->label_abx->setText(QString::number(ui->label_abx->text().toDouble() - 1));
        break;
    case 3: // 右
        ui->label_abx->setText(QString::number(ui->label_abx->text().toDouble() + 1));
        break;
    default:
        break;
    }
    updateRelativePositions();
}

void ControlForm::on_pushButton_addZPos_clicked() {
    double currentValue = ui->label_abz->text().toDouble();
    if(1==m_speedZLevel)
        currentValue = currentValue + 0.00001;
    else if(2==m_speedZLevel)
        currentValue = currentValue + 0.001;
    else if(3==m_speedZLevel)
        currentValue = currentValue + 0.01;
    if(currentValue > 150)
        currentValue = 150;
    ui->label_abz->setText(QString::number(currentValue));
    emit sig_labelChanged(ui->label_abz->text());
    ui->verticalSlider->setValue(static_cast<int>(currentValue*100000));
    updateRelativePositions();
}

void ControlForm::on_pushButton_minusZPos_clicked() {
    double currentValue = ui->label_abz->text().toDouble();
    if(1==m_speedZLevel)
        currentValue = currentValue - 0.00001;
    else if(2==m_speedZLevel)
        currentValue = currentValue - 0.001;
    else if(3==m_speedZLevel)
        currentValue = currentValue - 0.01;
    if(currentValue < -150)
        currentValue = -150;
    ui->label_abz->setText(QString::number(currentValue));
    emit sig_labelChanged(ui->label_abz->text());
    ui->verticalSlider->setValue(static_cast<int>(currentValue*100000));
    updateRelativePositions();
}

void ControlForm::handleSavePosClicked(QPushButton* clickedButton) {
    if (clickedButton->isChecked()) {
        // 记录当前绝对位置的值
        m_savedAbx = ui->label_abx->text().toDouble();
        m_savedAby = ui->label_aby->text().toDouble();
        m_savedAbz = ui->label_abz->text().toDouble();

        // 更新相对位置为 0.0000
        ui->label_rex->setText("0.0000");
        ui->label_rey->setText("0.0000");
        ui->label_rez->setText("0.0000");
    } else {
       // 根据按钮设置键名
       QString posKey;
       if (clickedButton == ui->pushButton_savePos1) {
           posKey = "Pos1";
       } else if (clickedButton == ui->pushButton_savePos2) {
           posKey = "Pos2";
       } else if (clickedButton == ui->pushButton_savePos3) {
           posKey = "Pos3";
       } else {
           posKey = "Pos1"; // 默认处理 Pos1
       }

        // 弹出提示窗口
        SavePosTipsDialog *dialog = new SavePosTipsDialog(posKey,this);
        dialog->setAttribute(Qt::WA_DeleteOnClose);

        connect(dialog, &SavePosTipsDialog::coverClicked, this, [this, clickedButton]() {
            // 覆盖逻辑
            ui->label_rex->setText("0.0000");
            ui->label_rey->setText("0.0000");
            ui->label_rez->setText("0.0000");

            ui->label_abx->setText(QString::number(m_savedAbx, 'f', 4));
            ui->label_aby->setText(QString::number(m_savedAby, 'f', 4));
            ui->label_abz->setText(QString::number(m_savedAbz, 'f', 4));
            emit sig_labelChanged(ui->label_abz->text());
            clickedButton->setChecked(true);
        });

        connect(dialog, &SavePosTipsDialog::deleteClicked, this, [this, clickedButton]() {
            // 删除逻辑
            m_savedAbx = 0.0;
            m_savedAby = 0.0;
            m_savedAbz = 0.0;
            ui->label_rex->setText("----");
            ui->label_rey->setText("----");
            ui->label_rez->setText("----");
            clickedButton->setChecked(false);
        });

        connect(dialog, &SavePosTipsDialog::renameClicked, this, &ControlForm::handleRenameClicked);
        dialog->exec();
    }
}

void ControlForm::on_pushButton_lockx_clicked(bool checked)
{
    ui->lineEdit_x->setEnabled(!checked);
}

void ControlForm::on_pushButton_locky_clicked(bool checked)
{
    ui->lineEdit_y->setEnabled(!checked);
}

void ControlForm::on_pushButton_lockz_clicked(bool checked)
{
    ui->lineEdit_z->setEnabled(!checked);
}

void ControlForm::handleRenameClicked(const QString& newName) {
    // 获取当前点击的按钮
    QPushButton* clickedButton = qobject_cast<QPushButton*>(sender());
    if (!clickedButton) {
        clickedButton = ui->pushButton_savePos1; // 默认处理 Pos1
    }

    // 根据按钮设置键名
    QString posKey;
    if (clickedButton == ui->pushButton_savePos1) {
        posKey = "Pos1";
    } else if (clickedButton == ui->pushButton_savePos2) {
        posKey = "Pos2";
    } else if (clickedButton == ui->pushButton_savePos3) {
        posKey = "Pos3";
    } else {
        posKey = "Pos1"; // 默认处理 Pos1
    }

    // 保存名称到成员变量
    m_savedPosNames[clickedButton] = newName;

    // 保存到配置文件
    QSettings settings("settings.ini", QSettings::IniFormat);
    settings.setValue(QString("Saved%1/Name").arg(posKey), newName);

    // 保存相对位置的 XYZ 值
    settings.setValue(QString("Saved%1/X").arg(posKey), ui->label_rex->text());
    settings.setValue(QString("Saved%1/Y").arg(posKey), ui->label_rey->text());
    settings.setValue(QString("Saved%1/Z").arg(posKey), ui->label_rez->text());
}

void ControlForm::on_pushButton_savePos1_clicked()
{
    handleSavePosClicked(ui->pushButton_savePos1);
}

void ControlForm::on_pushButton_savePos2_clicked()
{
    handleSavePosClicked(ui->pushButton_savePos2);
}

void ControlForm::on_pushButton_savePos3_clicked()
{
    handleSavePosClicked(ui->pushButton_savePos3);
}

